/**
 * 类名：用户业务类
 * 备注：负责用户的业务逻辑。
 * 作者：rankin
 * 日期：2016/03/4
 */
var User = require('../models/User');
var UserRole = require('../models/UserRole');
var UserPermission = require('../models/UserPermission');
var Box = require('../models/boxes');
var UserBox = require('../models/UserBox');
var Log = require('../models/log');
var Page = require('../models/page');

var _ = require('underscore');
var Promise = require("bluebird");

module.exports = {

    /**
     * 登陆接口
     */
    login: function (req, res, next) {

        var username = req.body.username;
        var password = req.body.pwd;
        User.findOne({user: username}).then(function (user) {
            if (!user) {
                return res.render('index', {
                    name: username,
                    pwd: req.body.password,
                    error: '用户名不存在！',
                    layout: false
                });
            }

            if (password != user.password) {
                return res.render('index', {
                    username: username,
                    pwd: req.body.password,
                    error: '密码不正确，请重新输入！',
                    layout: false
                });
            }

            //设置到会话中
            req.session.user = user;

            //查询角色
            return UserRole.find().in('_id', user.roles).exec();

        }).then(function (roles) {

            //查询权限
            if (roles.length > 0) {
                var all = _.pluck(roles, 'permissions');
                var permissions = _.uniq(_.flatten(all));
                return UserPermission.find().in('_id', permissions).exec();
            } else {
                return new Promise(function (resolve, reject) {
                    resolve([]);
                });
            }

        }).then(function (permissions) {

            var permissionMap = {};
            _.each(permissions, function (permission, index) {
                permissionMap[permission._id] = permission;
            })

            //赋值权限
            var user = req.session.user;
            req.session.permissionMap = permissionMap;
            req.session.permissions = permissions;

            //记录日志
            new Log({
                box_id: " ",
                user: req.session.user.user, //操作人
                date: new Date(), //操作日期
                operation: "登陆系统" //操作内容
            }).save();
            req.flash('success', '登陆成功.');

            return res.redirect('/box_management');

        }).error(function (err) {
            return res.render('index', {
                name: username,
                pwd: req.body.password,
                error: '服务器繁忙，请稍后再试！',
                layout: false
            });
        });
    },
    logout: function (req, res) {
        new Log({
            box_id: " ",
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "退出系统" //操作内容
        }).save();
        req.session.user = null;
        res.redirect('/');
    },
    to_update_pwd: function (req, res) {
        res.render('user/update_pwd', {});
    },
    do_update_pwd: function (req, res) {
        var opwd = req.body.opwd;
        var password = req.body.npwd1;
        var username = req.session.user.user;
        new User().findUserByName(username, function (err, datas) {
            if (err) {
                return res.render('user/update_pwd', {
                    error: '服务器繁忙，请稍后再试！'
                });
            }
            if (datas) {
                if (opwd != datas.password) {
                    return res.render('user/update_pwd', {
                        error: '旧密码不正确，请重新输入！'
                    });
                }
                new User().updatePwd(username, password, function (err) {
                    new Log({
                        box_id: " ",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "修改管理员密码" //操作内容
                    }).save();
                    req.flash('success', '密码修改成功.');
                    return res.redirect('/logout');
                });
            }
        });
    },
    list: function (req, res) {
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {}
        };
        new User().findForPage(obj, function (err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            res.render('user/user_list', {
                datas: datas,
                page: page
            });
        })
    },
    to_edit: function (req, res) {
        var id = req.query.id;
        //查询用户
        User.findOne({_id: id}).then(function (user) {
            if (user) {
                res.render('user/user_edit', {
                    user: user
                });
            } else {
                res.send({success: false, err: 'the user do not exists'});
            }
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    do_edit: function (req, res) {
        var id = req.body.id;
        //查询用户
        User.findOne({_id: id}).then(function (user) {
            if (user) {
                //更新字段
                _.extend(user, {
                    user: req.body.user,
                    phone: req.body.phone,
                    name: req.body.name,
                    company: req.body.company,
                    roles: req.body.roles,
                    password: req.body.password
                });
                //保存
                return user.save();
            } else {
                res.send({success: false, err: 'the user do not exists'});
            }
        }).then(function () {
            req.flash('success', '用户资料更新成功.');
            return res.redirect('/user/list?num=1');
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    to_create: function (req, res) {
        res.render('user/user_create');
    },
    do_create: function (req, res) {

        var username = req.body.username;

        User.findOne({user: username}).then(function (user) {
            if (user) {
                req.flash('error', '用户名已存在');
                return res.redirect('/user/create');
            } else {
                return new User({
                    user: req.body.username,
                    password: req.body.password,
                    company: req.body.company,
                    name: req.body.name,
                    phone: req.body.phone,
                    roles: req.body.roles,
                    create_date: new Date()
                }).save();
            }
        }).then(function (user) {
            return res.redirect('/user/list');
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    remove: function (req, res) {
        var buyerid = req.query.buyerid;
        var buyer = req.query.buyer;
        Box.find({owner: buyerid}).then(function (boxes) {
            if (boxes.length == 0) {
                return User.findOne({_id: buyerid}).remove().exec();
            } else {
                req.flash('error', '此用户已绑定箱子，不可删除.');
                res.redirect('/user/list?num=1');
            }
        }).then(function (user) {
            //保存日志
            return new Log({
                box_id: "",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "删除用户(用户名为:" + user.name + ")" //操作内容
            }).save();
        }).then(function () {
            res.redirect('/user/list?num=1');
        }).error(function (err) {
            res.send({success: false, err: err});
        });

    }
};

